﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebMvc.Controllers
{
    public class TokenController : Controller
    {
        
        [HttpPost]
        public JsonResult Index(string user,string pwd) {
            return Json(GetToken(user,pwd,DateTime.Now.AddDays(1)));
        }

        public JsonResult Check(string token) {
            return Json( Read(token));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        /// <param name="expires">过期时间</param>
        /// <returns></returns>
        public string GetToken(string user,string pwd,DateTime expires)
        {
            //var issuer = "localhost";   //发行者
            //var audience = "all";       //观众

            var xx = new List<System.Security.Claims.Claim>
        {
            new System.Security.Claims.Claim("name",user),
            new System.Security.Claims.Claim("password",pwd)
        };

            //1234567890123456 原值 //MTIzNDU2Nzg5MDEyMzQ1Ng== base64加密后
            var key = Convert.FromBase64String("MTIzNDU2Nzg5MDEyMzQ1Ng==");
            var now = DateTime.Now;  //现在时间
            

            var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key),
                "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                "http://www.w3.org/2001/04/xmlenc#sha256");

            var token = new JwtSecurityToken(null, null, xx, now, expires, signingCredentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public JwtSecurityToken Read(string token)
        {
            return new JwtSecurityToken(token);

            
        }
    }
}